package encaps.action;

import encaps.entities.Grant;
import encaps.entities.UserLocal;
import encaps.entities.UserLocalHome;
import encaps.logging.JMSUtil;
import encaps.logging.Log;
import encaps.resources.Labels;
import encaps.utils.EntityUtil;
import encaps.utils.MD5Hash;
import encaps.utils.SystemException;
import encaps.utils.XMLHelper;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import javax.ejb.FinderException;
import javax.naming.NamingException;
import org.jdom.Element;

public class LoginAction extends Action {

    public static final String LOGIN = "login";
    public static final String LOGIN_FIELD = "login";
    public static final String PASSWORD_FIELD = "password";
    private ActionContext actionContext;

    public LoginAction(ActionContext context, Grant requiredGrant) {
        actionContext = context;
        this.requiredGrant = requiredGrant;
    }

    @Override
    public Element execute() throws ActionExecutionException {
        Element e = null;
        String login = null;
        try {
            login = actionContext.getTextParameter(LOGIN_FIELD);
            String password = actionContext.getTextParameter(PASSWORD_FIELD);
            UserLocalHome userHome = EntityUtil.getUserHome();
            UserLocal user = userHome.findByLogin(login);

            if (!user.getPasswordHash().equals(MD5Hash.getHash(password))) {
                return XMLHelper.createTextMessage(Labels.getLabel(Labels.AUTHORIZATION_FAILED_WRONG_PASSWORD_MESSAGE));
            }
            actionContext.setUserRole(user.getRole());
            actionContext.setUserLogin(login);

            JMSUtil.sendLogMessage(Log.LOGIN,
                    EntityUtil.getUserHome().findByLogin(login).getID(), login,
                    new Date(), null, null, null);

            e = XMLHelper.createTextMessage(Labels.getLabel(Labels.WELCOME));
            return e;
        } catch (NamingException ex) {
            throw new ActionExecutionException(ex);
        } catch (FinderException ex) {
            return XMLHelper.createTextMessage(Labels.getLabel(Labels.AUTHORIZATION_FAILED_NO_SUCH_USER_MESSAGE) + ": " + login);
        } catch (SystemException ex) {
            return XMLHelper.createTextMessage(ex.getMessage());
        } catch (NoSuchAlgorithmException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.AUTHORIZATION_FAILED_PASSWORD_ENCODING_ERROR_MESSAGE), ex);
        } catch (UnsupportedEncodingException ex) {
            throw new ActionExecutionException("Authorization error", ex);
        } finally {
            actionContext = null;
        }
    }
}
